<template>
  <div>
    <div :class="`view-task-detail ${tabList?.length > 0 ? 'view-task-detail-edit' : ''}`">
      <div class="view-task-title">
        <px-button type="primary" icon="ArrowLeft" @click="handleGoBack">返回</px-button>
        <div class="text">{{ data.taskName }}</div>
        <px-tag class="ml-2" :type="tagArr[data['taskStatus']]">{{ data["taskStatusDesc"] }}{{ data.timeOut === 1 ? "(超期)" : "" }}</px-tag>
        <!-- <div v-show="!!data.taskStatusDesc" class="status">
          <div class="circle" :style="{ backgroundColor: `${TAG_CONFIG[data.taskStatus]?.color}` }" />
          <p :style="{ color: `${TAG_CONFIG[data?.taskStatus]?.color}` }">{{ data.taskStatusDesc }}</p>
          <p v-if="data.timeOut === 1" :style="{ color: '#EF4444', marginLeft: '4px' }">超期</p>
        </div> -->
      </div>
      <div v-if="data?.taskStatus === 6">
        <px-button
          v-show="USER_ROLE.isExecutor(data)"
          v-has="'ERC_INSPECT_TASK_TRANSFER_REVIEW'"
          type="primary"
          plain
          @click="() => (changeAcceptorVisible = true)"
          >转审</px-button
        >
        <px-button
          v-show="USER_ROLE.isAccepter(data)"
          v-has="'ERC_INSPECT_TASK_EXAMINE'"
          type="primary"
          @click="() => (submitCheckResultVisible = true)"
          >签字验收</px-button
        >
        <px-button v-show="USER_ROLE.isoperator(data)" v-has="'ERC_INSPECT_TASK_EXAMINE_WITHDRAW'" type="primary" @click="handleTaskBack(data)"
          >撤回审核</px-button
        >
      </div>
    </div>
    <CustomTabs v-if="tabList?.length > 0" :tabList="tabList" :activeName="activeName" style="margin-bottom: 12px" @tabSelect="handelTabSelected" />
    <div v-show="activeName === 'task'" :class="`view-flex ${tabList?.length > 0 ? 'view-flex-edit' : ''}`" v-bind="$attrs">
      <px-scrollbar ref="scrollbarRef" class="inspect-task-detail-content" @scroll="handleScroll">
        <div ref="basicsRef">
          <div class="view-equip-title">基础信息</div>
          <ColumnsTable :columns="INSPECTTASKDETAIL_BASEINFO_COLUMNS" :data="data">
            <template #value="{ scope }">
              <template v-if="scope.prop === 'checkAreaDesc' && data.checkAreaDesc">
                <px-tag
                  v-for="(item, index) in data.checkAreaDesc.split(',')"
                  :key="index"
                  class="ml-2"
                  style="margin-top: 2px; margin-bottom: 2px"
                  type="info"
                  >{{ item }}</px-tag
                >
              </template>
              <template v-if="scope.prop === 'checkType' && data.checkType">
                {{ dealCheckTypeName(data.checkType) }}
              </template>
            </template>
          </ColumnsTable>
        </div>
        <div ref="contentRef" class="view-mb20">
          <div class="view-equip-title">巡检作业内容</div>
          <div v-if="data.checkJobContentList && data.checkJobContentList?.length > 0">
            <EditDropDown
              v-for="eqpItem in data.checkJobContentList"
              ref="ruleChildrenRef"
              :key="eqpItem.eqpId"
              :dropdownTitle="`${eqpItem.eqpName}（${eqpItem.eqpId}）`"
            >
              <template v-slot:content>
                <SubEditDropDown
                  v-for="(ruleItem, index) in eqpItem.checkContentList"
                  :key="`SubEditDropDown${index}`"
                  :dropdownTitle="`${ruleItem.checkTaskRuleContent}`"
                >
                  <template v-slot:content>
                    <px-table :data="ruleItem.list" style="margin-bottom: 18px" class="equip-table inner-tabel" size="small" max-height="400" border>
                      <px-table-column
                        v-for="(item, index) in tableColumns"
                        :key="`table${index}`"
                        :label="item.label"
                        :prop="item.prop"
                        :min-width="item.minWidth"
                        :align="item.align"
                        :show-overflow-tooltip="item.showOverflowTooltip"
                        :fixed="item.fixed"
                      />
                    </px-table>
                  </template>
                </SubEditDropDown>
              </template>
            </EditDropDown>
          </div>
        </div>
        <div ref="resultRef">
          <div class="view-equip-title">巡检总结</div>
          <ColumnsTable :columns="summaryTableColumns" :data="data">
            <template #value="{ scope }">
              <template v-if="scope.prop === 'fileList'">
                <PhotoUpload photoType="view" :photoData="{}" :photoList="fileList" />
              </template>
            </template>
          </ColumnsTable>
        </div>
        <div v-if="data.taskStatus === 3" ref="acceptRef">
          <div class="view-equip-title">审核结果</div>
          <ColumnsTable :columns="acceptTableColumns" :data="data">
            <template #value="{ scope }">
              <template v-if="scope.prop === 'acceptSignatureFile'">
                <PhotoUpload photoType="view" :photoData="{}" :photoList="acceptSignatureFile" />
              </template>
            </template>
          </ColumnsTable>
        </div>
      </px-scrollbar>
      <WidgetRouter :router-list="routerList" :scrollbar-ref="scrollbarRef" :scroll-top="scrollTop" />
    </div>

    <PlanForm v-show="activeName === 'plan'" :planNo="data.planNo" :taskNo="data.taskNo" />
    <MaintainTable v-if="activeName === 'maintain'" :data="maintainTableData" />
    <!-- 审核 -->
    <SubmitCheckResult
      v-if="submitCheckResultVisible"
      v-model:dialogVisible="submitCheckResultVisible"
      :moduleName="moduleName"
      :data="data"
      @refresh="emits('refresh')"
    />
    <!-- 转审 -->
    <ChangeAcceptor v-if="changeAcceptorVisible" v-model:dialogVisible="changeAcceptorVisible" :data="data" @refresh="emits('refresh')" />
  </div>
</template>

<script setup lang="ts">
import { taskBack } from "@/api/erc/inspectTask";
import CustomTabs from "@/components/Tabs/index.vue";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import { debounce } from "@pureadmin/utils";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, reactive, ref, toRef, toRefs, watchEffect } from "vue";
import { useRoute, useRouter } from "vue-router";
import ColumnsTable from "../../components/ColumnsTable.vue";
import SubEditDropDown from "../../components/SubEditDropDown.vue";
import { WidgetRouter } from "../../components/index";
import { INSPECTTASKDETAIL_BASEINFO_COLUMNS, TAB_LIST, USER_ROLE } from "../config";
import ChangeAcceptor from "./ChangeAcceptor.vue";
import MaintainTable from "./MaintainTable.vue";
import PlanForm from "./PlanForm.vue";
import SubmitCheckResult from "./SubmitCheckResult.vue";
const emits = defineEmits(["refresh", "backMainPage"]);
const activeName = ref("task");
const route = useRoute();
const router = useRouter();
const props = defineProps(["data", "tableData", "tableEqiupSelected", "disabled", "moduleName", "maintainTableData"]);
const tagArr = ["info", "warning", "primary", "success", "success", "primary"];
const tabList = computed(() => {
  if (props.maintainTableData.length) {
    // 已完成且存在维修工单
    if (props.data?.taskType === 1) {
      // 计划生成
      return [...TAB_LIST, { name: "maintain", label: "巡检维修信息" }];
    } else {
      // 临时任务
      return [
        { name: "task", label: "巡检任务" },
        { name: "maintain", label: "巡检维修信息" }
      ];
    }
  } else {
    // 不存在维修工单
    if (props.data?.taskType === 1) {
      // 计划生成
      return TAB_LIST;
    } else {
      // 临时任务
      return [];
    }
  }
});
const state = reactive<any>({
  tableColumns: [
    { prop: "checkItem", label: "巡检项", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
    { prop: "checkContent", label: "巡检内容", minWidth: "160", showOverflowTooltip: true },
    { prop: "result", label: "巡检结果", minWidth: "160", showOverflowTooltip: true },
    { prop: "executeByName", label: "执行人", minWidth: "160", showOverflowTooltip: true },
    { prop: "execTime", label: "执行时间", minWidth: "200", showOverflowTooltip: true }
  ],
  submitCheckResultVisible: false,
  changeAcceptorVisible: false,
  summaryTableColumns: [
    [
      {
        label: "总结",
        value: "summary"
      }
    ],
    [
      {
        label: "照片",
        value: "fileList"
      }
    ]
  ],
  acceptTableColumns: [
    [
      {
        label: "验收人",
        value: "acceptor"
      },
      {
        label: "验收时间",
        value: "acceptTime"
      }
    ],
    [
      {
        label: "验收意见",
        value: "acceptOpinion"
      }
    ],
    [
      {
        label: "验收签字",
        value: "acceptSignatureFile"
      }
    ]
  ]
});
const { tableColumns, summaryTableColumns, acceptTableColumns, submitCheckResultVisible, changeAcceptorVisible } = toRefs(state);
const fileList = computed(() => {
  return props.data?.fileList?.map(item => ({ ...item, url: item.fileUrl }));
});
const acceptSignatureFile = computed(() => {
  return props.data?.acceptSignatureFile?.map(item => ({ ...item, url: item.fileUrl }));
});
const checkTypeArr = { equipment: "设备巡检", environment: "环境巡检" };
const dealCheckTypeName = checkType => {
  if (!checkType || !checkType.length) return "";
  return checkType.reduce((acc, cur) => {
    if (!acc) return checkTypeArr[cur];
    return acc + "," + checkTypeArr[cur];
  }, "");
};
// 点击tab显示页面详情
const handelTabSelected = selectName => {
  activeName.value = selectName;
};
// 返回上一级
const handleGoBack = () => {
  if (route.query.taskNo) {
    // 其他页面进入详情，返回其他页面
    router.go(-1);
  } else {
    emits("backMainPage");
  }
};
// 撤回审核
const handleTaskBack = (row: any) => {
  const { taskNo } = row;
  PxMessageBox.confirm(`确认撤回审核吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await taskBack(taskNo);
      PxMessage.success("撤回成功");
      emits("refresh");
    })
    .catch(() => {});
};
//右侧滚动导航
const scrollbarRef = ref(null);
const routerList = ref([]);
const scrollTop = ref();
//折叠面板ref
const basicsRef = ref(null);
const contentRef = ref(null);
const ruleChildrenRef = ref(null);
const resultRef = ref(null);
const acceptRef = ref(null);
//右侧滚动导航相关函数
const handleScroll = debounce(({ scrollTop: curScrollTop }) => {
  scrollTop.value = curScrollTop;
}, 200);
const scrollInit = () => {
  let routerName = "基本信息,巡检作业内容,巡检总结";
  let routerRefs = [basicsRef, contentRef, resultRef];
  let children = null;
  if (props.data.taskStatus === 3) {
    // 已完成
    routerName = "基本信息,巡检作业内容,巡检总结,审核结果";
    routerRefs = [basicsRef, contentRef, resultRef, acceptRef];
  }
  if (props.data && ruleChildrenRef.value) {
    children = props.data.checkJobContentList?.map((item, index) => {
      return { ref: toRef(ruleChildrenRef.value[index]?.$el), name: item.eqpName };
    });
  }

  routerList.value = routerName.split(",").map((item, index) => {
    if (item === "巡检作业内容") {
      return { ref: routerRefs[index], name: item, children };
    } else {
      return { ref: routerRefs[index], name: item };
    }
  });
};
watchEffect(() => {
  scrollInit();
});
// onBeforeMount(() => {
//   scrollInit();
// });
</script>

<style lang="scss" scoped>
.view-task-detail {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;

  &.view-task-detail-edit {
    padding-bottom: 0;
  }

  .view-task-title {
    display: flex;
    flex-direction: row;
    align-items: center;

    .text {
      margin-left: 20px;
      font-size: 20px;
      font-weight: 600;
      color: rgb(0 0 0 / 90%);
    }

    .status {
      display: flex;
      flex-direction: row;
      align-items: center;

      .circle {
        width: 8px;
        height: 8px;
        margin-right: 5px;
        margin-left: 8px;
        border-radius: 50%;
      }
    }
  }
}

.view-flex {
  position: relative;
  display: flex;
  height: calc(100vh - 210px);

  &.view-flex-edit {
    height: calc(100vh - 260px);

    .view-task-detail {
      padding-top: 16px;
      padding-bottom: 0;
    }
  }

  .view-equip-title {
    height: 22px;
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: bold;
    line-height: 22px;
    color: rgb(0 0 0 / 80%);
  }

  :deep(.inner-tabel) {
    width: 100%;

    .px-table__header thead tr th {
      font-size: 14px;
      font-weight: bold;
      color: #000;
      background-color: #e7eefb !important;
    }

    td.px-table__cell div {
      width: 100%;
    }
  }

  :deep(.inspect-task-detail-content) {
    width: 100%;
    min-width: 500px;
  }

  :deep(.px-table__header) {
    .must::before {
      margin-right: 4px;
      color: var(--px-color-danger);
      content: "*";
    }
  }
}

.view-mb20 {
  margin-bottom: 20px;
}
</style>
